package com.kewill.jira.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

/**
 * Created by YanJun on 2016/7/15.
 */
public class FileUtil {
    public static void delDir(File dir) {
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    delDir(files[i]);
                } else {
                    files[i].delete();
                }
            }
            dir.delete();
        }
    }
    public static void copyFileToDir(File file, File dir) {
        if (file.exists() && dir.exists() && dir.isDirectory()) {
            FileChannel srcCh = null;
            try {
                srcCh = new FileInputStream(file).getChannel();
                FileChannel destCh =
                        new FileOutputStream(new File(dir.getPath() + File.separator + file.getName()))
                                .getChannel();
                destCh.transferFrom(srcCh, 0, srcCh.size());
                srcCh.close();
                destCh.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static void mergeDir(File src, File dest) {
        if (src.isDirectory() && dest.isDirectory()) {
            File[] files = src.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (files[i].isDirectory()) {
                    mergeDir(files[i], src);
                } else {
                    copyFileToDir(files[i], dest);
                }
            }
            delDir(src);
        }
    }
}
